import json

import sql
from websocket_information import WebSocketController


def get_types(ws, uuid):
    try:
        article_info = {}
        data = json.loads(json.dumps(article_info))
        data['uuid'] = uuid
        types = sql.show_type()
        types_list = []
        for t in types:
            type_info = {'type_id': t[0], 'type_name': t[1]}
            types_list.append(type_info)
        data['message'] = types_list
        article = json.dumps(data, ensure_ascii=False)
        print(article)
        WebSocketController.on_send(ws, article)
    except Exception as e:
        print(e)


def get_type_by_id(ws, uuid, message):
    try:
        article_info = {}
        data = json.loads(json.dumps(article_info))
        data['uuid'] = uuid
        type = sql.get_type_info(message)
        type_info = {'type_id': type[0],
                     'type_name': type[1]}
        data['message'] = type_info
        article = json.dumps(data, ensure_ascii=False)
        WebSocketController.on_send(ws, article)
    except Exception as e:
        print(e)


def add_type(ws, uuid, message):
    try:
        article_info = {}
        data = json.loads(json.dumps(article_info))
        data['uuid'] = uuid
        type_name = message['type_name']
        res = sql.add_type(type_name)
        if res > 0:
            data['message'] = 1
        else:
            data['message'] = -1
        article = json.dumps(data, ensure_ascii=False)
        WebSocketController.on_send(ws, article)
    except Exception as e:
        print(e)


def update_type(ws, uuid, message):
    try:
        article_info = {}
        data = json.loads(json.dumps(article_info))
        data['uuid'] = uuid
        type_id = message['type_id']
        type_name = message['type_name']
        res = sql.modify_type(type_id, type_name)
        if res > 0:
            data['message'] = 1
        else:
            data['message'] = -1
        article = json.dumps(data, ensure_ascii=False)
        WebSocketController.on_send(ws, article)
    except Exception as e:
        print(e)


def delete_type(ws, uuid, message):
    try:
        article_info = {}
        data = json.loads(json.dumps(article_info))
        data['uuid'] = uuid
        res = sql.delete_type(message)
        if res > 0:
            data['message'] = 1
        else:
            data['message'] = -1
        article = json.dumps(data, ensure_ascii=False)
        WebSocketController.on_send(ws, article)
    except Exception as e:
        print(e)
